<?php

namespace app\admin\controller;

use Common;
use think\Db;
use app\common\controller\Backend;
use app\admin\model\QianbaoSysetmAddr;
/**
 * 1.03 区块链币日志管理
 *
 * @icon fa fa-circle-o
 */
class QianbaoSysetmLog extends Backend
{
    
    /**
     * QianbaoSysetmLog模型对象
     * @var \app\admin\model\QianbaoSysetmLog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\QianbaoSysetmLog;

        $eth_kgf =  db('rtp')->where('type','kgf')->value('price');
        $this->assign('guiji_kgf',config('site.guiji_kgf'));
        $this->assign('eth_kgf',$eth_kgf);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function withdraw_money_request($id = NULL)
    {   

        if(!$id){
            $id = input('ids');
        }

        Db::startTrans();

            $user_qianbao = $this->model->where('id', $id)->where('type',2)->whereIn('zt',('2,3,5'))->lock(true)->find();

            if(!$user_qianbao){
                $this->error('该账户无需提币，请刷新');
            }
            
            if(!$user_qianbao->money || !$user_qianbao->toaddr || !$user_qianbao->bizhong){
                $this->error('地址信息有误，请检查');
            }
            if(!config('site.erc_contract')[strtoupper($user_qianbao->bizhong)] || !config('site.erc_decimal')[strtoupper($user_qianbao->bizhong)]){
                $this->error('系统配置信息有误，请检查');
            }

            if(strlen($user_qianbao['toaddr']) != 42){
                $this->error('收款人地址长度不对');
            }

            $tokenbalance =  $this->tokenbalance($user_qianbao);
            if(abs($user_qianbao->money) > $tokenbalance ){
                $this->error('你的转账账户'.strtoupper($user_qianbao->bizhong).'余额不足,请充值在转账');
            }

            $getbalance =  $this->getbalance($user_qianbao);
            $eth_kgf =  db('rtp')->where('type','kgf')->value('price');
            if($eth_kgf > $getbalance ){
                $this->error('你的转账账户'.strtoupper($user_qianbao->bizhong).'余额不足,请充值在转账');
            }

            $rsp = $this->transfer($user_qianbao);
            if ($rsp['code'] == 1) {
                $ret = $this->model->update(['id' => $id, 'hash' => $rsp['data'] ,'zt' => '4', 'time_cl' => time()]);
                if($ret){
                    Db::commit();
                    $this->success('提币转账正在处理中');
                }else{
                    Db::rollback();
                    $this->error('提交失败');
                }
            }else{
                $this->error('提交失败');
            }

    }

    //执行链上转账
    public function transfer($user_qianbao)
    {   
        // $eth_kgf =  db('rtp')->where('type','kgf')->value('price');
        
        $eth_kgf = config('site.guiji_kgf');

        $url = cbtapi().'transfer';
        $data['apikey']= config('cbtapi')['apikey'];
        $data['privatekey'] = config('accounts')['privatekey']; // 私钥
        $data['contractaddress'] = config('site.erc_contract')[strtoupper($user_qianbao->bizhong)]; // 合约地址
        $data['value'] = abs($user_qianbao->money); // 代币数量
        // $data['gasprice'] = '0.002'; // 手续费参考0.0012 ETH‬
        $data['gasprice'] = $eth_kgf; // 手续费
        $data['to'] = $user_qianbao->toaddr; //收款账号
        $data['unit'] = config('site.erc_decimal')[strtoupper($user_qianbao->bizhong)]; //长度单位
       
        //发送
        $result = http($url,$data);
        $rsp = json_decode($result, true);
        return $rsp;
        
    }

    // 查询代币余额
    public function tokenbalance($user_qianbao)
    {
        $url = cbtapi().'tokenbalance';
        $data['apikey']= config('cbtapi')['apikey'];
        $data['contractaddress'] = config('site.erc_contract')[strtoupper($user_qianbao->bizhong)]; // 合约地址
        $data['address'] = config('accounts')['addr']; 
        $data['unit'] = config('site.erc_decimal')[strtoupper($user_qianbao->bizhong)]; //长度单位

        $result = http($url,$data);
        $rsp = json_decode($result, true);
        if ($rsp['code'] == 1) {
            return $rsp['data'];
        }else{
            $this->error($rsp['msg']);
        } 
    }

    // 查询eth余额
    public function getbalance($user_qianbao)
    {
        $url = cbtapi().'getbalance';
        $data['address'] = config('accounts')['addr']; //账号
        $data['apikey']= config('cbtapi')['apikey'];
        $result = http($url,$data);
        $rsp = json_decode($result, true);

        if ($rsp['code'] == 1) {
            return $rsp['data'];

        }else{
            $this->error('重新提交');
        } 
    }

    // 提币驳回 zt=2（链上到账失败）的需要驳回怎么办？继续转，直到成功为止。
    public function bohui()
    {   
        $id = input('ids');
        $user_qianbao = $this->model->where('id',$id)->where('type',2)->whereIn('zt',('2,3'))->find();

        if(!$user_qianbao){
            $this->error('该账户无须被驳回，请刷新');
        }
        // 启动事务
        Db::startTrans();
        try {   

            if(!$this->model->where('id',$id)->update(['zt' => 0,'note' => '审核不通过'])){
                throw new \Exception("数据未更新，请检查是否正确",1);
            };
            if(!db('user')->where('id',$user_qianbao['uid'])->setInc($user_qianbao['bizhong'],abs($user_qianbao['money']) + $user_qianbao['charge'])){
                throw new \Exception("数据未更新，请检查是否正确",2);
            }
            
            Db::commit(); 
        } catch (\Exception  $e) {
            Db::rollback(); //km++
            $this->error($e->getMessage());
            // $this->error($e->getcode());
            // die(); // 终止异常
        }
        $this->success('驳回成功');

    }

    // 自动检测处理订单是否成功到账 $txid=最新的hash（如果上一笔提币链上失败，后台选择重新发起一笔提币 新hash更新 不允许链上失败最终出现在数据库，只有驳回）
    public function processing($id, $txid,$timeout=600,$interval=15)
    {   
        sleep(5);
        $t0 = time();
		while(true){
            //查询交易是否到账 0查询失败，1交易成功，2交易失败，3交易中
            $receipt = erc_daozhang($txid);
            // 失败
			if($receipt['zt'] == 2){
                db('qianbao_sysetm_log')->where('id',$id)->update(['hash' => $txid ,'zt' => '2','note' => '提币转账失败']);
                break;
            // 成功
            }elseif($receipt['zt'] == 1){
                db('qianbao_sysetm_log')->where('id',$id)->update(['hash' => $txid ,'zt' => '4']);
                break;
            }
			if((time() - $t0) > $timeout) break;
			sleep($interval);  
		}
        
    }


    // 确认入账
    public function disable()
    {   
        $id = input('ids');
        $user_qianbao = $this->model->where('id',$id)->where('type',4)->whereIn('disable',1)->find();
        if($user_qianbao){
            try {
                $a1 =db('user')->where('id',$user_qianbao['uid'])->setInc('usdt',$user_qianbao['money']);
                $a2 = $this->model->update(['id' => $user_qianbao['id'], 'disable' => 0]);
                if(!$a1 && !$a2){
                    throw new \Exception("确认入账失败", 1);
                }
                Db::commit(); 
            } catch (\Exception $th) {
                Db::rollback(); //km++
                $this->error($th->getMessage());
            }
            $this->success('确认入账成功');
        }
        $this->error('请刷新!');
    }


    // BHD提币成功，不进过链上，状态改变
    public function bhd_money_request()
    {   
        $id = input('ids');
        $user_qianbao = $this->model->where('id', $id)->where('type',2)->whereIn('zt',('2,3'))->lock(true)->find();
        if(!$user_qianbao){
            $this->error('该账户无需提币，请刷新');
        }
        if($user_qianbao){
            try {
                $a1 = $this->model->update(['id' => $user_qianbao['id'],'zt' => '1', 'time_cl' => time()]);
                if(!$a1){
                    throw new \Exception("提币失败", 1);
                }
                Db::commit(); 
            } catch (\Exception $th) {
                Db::rollback();
                $this->error($th->getMessage());
            }
            $this->success('提币成功');
        }
        $this->error('请刷新!');

    }


}
